<template>
  <el-drawer
    ref="drawerRef"
    :title="$t('message.xzhy2')"
    :visible.sync="isShowMember"
    :before-close="closeDrawer"
    size="50%"
  >
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :rules="rulers"
        :model="param"
        label-width="auto"
        label-suffix="："
        @submit.native.prevent
      >
        <el-form-item :label="$t('message.sjhm')" prop="phone">
          <el-input
            v-model="param.phone"
            type="text"
            onkeyup="value=value.replace(/[^\d^]/g,'')"
            :placeholder="$t('message.qsr') + $t('message.sjh')"
            maxlength="11"
            class="w400"
            @blur="photoBlur"
          />
        </el-form-item>
        <el-form-item :label="$t('message.nc')" prop="nickName">
          <el-input
            v-model="param.nickName"
            type="text"
            class="w400"
            :placeholder="$t('message.qsr') + $t('message.nc')"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('message.zsxm')">
          <el-input
            v-model="param.realName"
            :placeholder="$t('message.qsr') + $t('message.nc')"
            class="w400"
          />
        </el-form-item>
        <el-form-item :label="$t('message.csrq')">
          <el-date-picker
            v-model="param.birthday"
            class="w400"
            value-format="yyyy-MM-dd"
            type="date"
            :placeholder="$t('message.qxz') + $t('message.csrq')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sex')">
          <el-radio v-model="param.sex" label="1">{{
            $t("message.nan")
          }}</el-radio>
          <el-radio v-model="param.sex" label="2">{{
            $t("message.nv")
          }}</el-radio>
          <el-radio v-model="param.sex" label="0">{{
            $t("message.bm")
          }}</el-radio>
        </el-form-item>
        <!-- <el-form-item :label="$t('message.sfzh')" prop="identityNumber"> -->
        <el-form-item :label="$t('message.sfzh')">
          <el-input
            v-model="param.identityNumber"
            type="text"
            class="w400"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            :placeholder="$t('message.qsr') + $t('message.sfzhm')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.rlcj')" prop="showFaceUrl">
          <div class="df_ac">
            <div class="img_warp">
              <img
                :src="param.showFaceUrl ? param.showFaceUrl : faceimg"
                class="mr20"
                style="width: 80px; height: 80px"
                alt=""
              />
              <div v-show="param.showFaceUrl" class="delete pointer">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
            <el-button
              :loading="caijiLoading"
              type="primary"
              @click="acquisitionFace"
              >{{ $t("message.caji") }}</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-camera"
              class="mr10"
              @click="openCamera"
              >{{ $t("message.pashi") }}</el-button
            >
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <el-button type="primary" icon="el-icon-upload2">{{
                $t("message.upload")
              }}</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.kmkh')" prop="chipNumber">
          <el-input
            v-model="param.chipNumber"
            class="entitycard-style w400"
            :placeholder="$t('message.qsr') + $t('message.kmkh')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.xpkh')" prop="entityNumber">
          <el-input
            v-model="param.entityNumber"
            class="entitycard-style w400"
            :placeholder="$t('message.qsr') + $t('message.cjxpkh')"
          />
          <el-button
            class="entitycard-btn-style"
            type="primary"
            @click="getCardNum"
            >{{ $t("message.caji") }}</el-button
          >
        </el-form-item>
        <el-form-item :label="$t('message.jymm')">
          <el-input
            v-model="param.payPw"
            type="password"
            onkeyup="value=value.replace(/[^\d^]/g,'')"
            oninput="if(value.length>6)value=value.slice(0,6)"
            :placeholder="$t('message.qsr') + $t('message.jymm')"
            show-password
            class="w400"
            auto-complete="new-password"
          />
        </el-form-item>
        <el-form-item :label="$t('message.qrjymm')">
          <el-input
            v-model="param.enSurePwd"
            type="password"
            show-password
            onkeyup="value=value.replace(/[^\d^]/g,'')"
            oninput="if(value.length>6)value=value.slice(0,6)"
            :placeholder="$t('message.qqrjymm')"
            class="w400"
            auto-complete="new-password"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="true"
            v-preventReClick
            :loading="subLoading"
            type="primary"
            @click="onSubmit('kaika')"
            >{{ $t("message.bchybkk") }}</el-button
          >
          <el-button
            v-preventReClick
            :loading="subLoading2"
            @click="onSubmit('save')"
            >{{ $t("message.bchybtc") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <transition name="fade">
      <Cropper
        v-if="dialogCropperVisible"
        :option-img="optionImg"
        :fileinfo="fileinfo"
        use-type="MEMBER_IMG"
        :fixed-number="[500, 500]"
        @formSubmit="cropperSubmit"
        @formClose="cropperClose"
      />
    </transition>
    <el-dialog
      :title="$t('message.pashi')"
      :visible.sync="paisheModal"
      width="760px"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      append-to-body
      @close="closeCamera"
    >
      <video
        v-show="isShowCamera"
        id="videoCamera"
        :width="videoWidth"
        :height="videoHeight"
      />
      <canvas
        v-show="!isShowCamera"
        id="canvasCamera"
        style="display: none"
        :width="videoWidth"
        :height="videoHeight"
      />
      <span slot="footer">
        <div>
          <el-button @click="closeCamera">{{ $t("message.qx") }}</el-button>
          <el-button
            v-show="blobFileCamera"
            type="primary"
            @click="resetCamera"
            >{{ $t("message.chonpa") }}</el-button
          >
          <el-button
            v-show="blobFileCamera"
            :loading="cameraLoading"
            type="primary"
            @click="enterCamera"
            >{{ $t("message.ksjc") }}</el-button
          >
          <el-button
            v-show="!blobFileCamera"
            type="primary"
            @click="setImage"
            >{{ $t("message.pashi") }}</el-button
          >
        </div>
      </span>
    </el-dialog>

    <CropperCopy
      v-if="isShowCropper"
      :option-img="blobFileCamera"
      use-type="MEMBER_IMG"
      :fixed-number="[500, 500]"
      @formSubmit="cropperSubmit"
      @formClose="cropperCameraClose"
    />
    <!-- <Camera :tack-photo="tackPhoto" /> -->
  </el-drawer>
</template>

<script>
import Cropper from "@/components/cropper";
import CropperCopy from "./cropper.vue";
import {
  uploadFile,
  memberRegister,
  collectFace,
  collectCard,
  memberList,
  // memberDetailInfo
} from "@/api";
export default {
  name: "MemberAdd",
  components: {
    Cropper,
    CropperCopy,
  },
  data() {
    return {
      isShowCamera: true,
      cameraLoading: false,
      videoWidth: 700,
      videoHeight: 525,
      mediaStreamCamera: "",
      blobFileCamera: "",
      isShowCropper: false,
      // 以上是拍摄
      isShowMember: false,
      modalDialog: this.$store.getters.dialog,
      caijiModal: false,
      caijiLoading: false,
      paisheModal: false,
      subLoading: false,
      subLoading2: false,
      meta: [],
      param: {
        nickName: null,
        phone: null,
        vcode: null,
        realName: null,
        entityNumber: null,
        sex: "0",
        identityNumber: null,
        payPw: null,
        enSurePwd: null,
        cardTypeId: null,
        venueId: sessionStorage.getItem("venueId"),
      },
      rulers: {
        phone: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sjh"),
            trigger: "change",
          },
          {
            min: 11,
            max: 11,
            message: this.$t("message.cd11"),
            trigger: "blur",
          },
        ],
        nickName: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.nc"),
            trigger: "blur",
          },
          {
            min: 1,
            max: 8,
            message: this.$t("message.cdydb"),
            trigger: "blur",
          },
        ],
        // vcode: [{ required: true, message: this.$t('message.qsr') + this.$t('message.yzm'), trigger: 'blur' }],
        identityNumber: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.sfzh"),
            trigger: "blur",
          },
          {
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: this.$t("message.qsrzqdsfzh"),
            trigger: "blur",
          },
        ],
        // showFaceUrl: [
        //   { required: true, message: this.$t('message.qcjrl'), trigger: 'blur' }
        // ],
        realName: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.zsxm"),
            trigger: "blur",
          },
        ],
      },
      faceimg: require("@/assets/images/default_faceid.png"),
      dialogCropperVisible: false,
      optionImg: "",
      files: {},
      fileinfo: {},
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: "MEMBER_IMG",
      },
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    photoBlur(e) {
      const value = e.target.value;
      if (value.length === 11) {
        const pagination = { page: 1, rows: 1 };
        memberList({ param: { keyword: value }, pagination }).then((res) => {
          if (res.errorCode !== "000000") return;
          if (res.recordList.length > 0 && !res.recordList[0].cardTypeId) {
            this.$confirm(this.$t("message.sfkktc"), this.$t("message.ts"), {
              confirmButtonText: this.$t("message.qd"),
              cancelButtonText: this.$t("message.qx"),
              type: "warning",
            }).then(() => {
              this.isShowMember = false;
              this.$refs.drawerRef.closeDrawer();
              this.$emit("submit", res.recordList[0]);
            });
          } else if (
            res.recordList.length > 0 &&
            res.recordList[0].cardTypeId
          ) {
            this.$message.warning(this.$t("message.gyhyjktbkk"));
          }
        });
      }
    },
    onSubmit(str) {
      const { param } = this;
      if (param.enSurePwd || param.payPw) {
        if (param.enSurePwd && param.payPw) {
          if (param.enSurePwd !== param.payPw) {
            return this.$message.warning(this.$t("message.jymmlcbyz"));
          }
        } else {
          return this.$message.warning(this.$t("message.jymmlcbyz"));
        }
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.subLoading = str === "kaika";
          this.subLoading2 = str === "save";
          memberRegister({
            param: this.param,
          }).then(
            (res) => {
              this.subLoading = false;
              this.subLoading2 = false;
              if (res.errorCode !== "000000") return;
              this.$message.success(this.$t("message.hyzccg"));
              if (str === "kaika") {
                this.isShowMember = false;
                this.$refs.drawerRef.closeDrawer();
                this.$emit("submit", res.record);
                this.$emit("successXzhy", res.record);
                this.$emit("success");
              } else if (str === "save") {
                this.isShowMember = false;
                this.$refs.drawerRef.closeDrawer();
                this.$emit("success");
                this.$emit("successXzhy", res.record);
              }
            },
            () => {
              this.subLoading = false;
              this.subLoading2 = false;
            }
          );
        } else {
          // this.isShowMember = false
          // this.$refs.drawerRef.closeDrawer()
        }
      });
    },
    closeDrawer() {
      this.isShow = false;
      this.$emit("close");
    },
    // 打开相机
    openCamera() {
      this.paisheModal = true;
      this.isShowCamera = true;
      const that = this;
      this.$nextTick(() => {
        var mediaOpts = { audio: false, video: true };
        navigator.mediaDevices
          .getUserMedia(mediaOpts)
          .then(function (stream) {
            that.mediaStreamCamera = stream;
            const video = document.querySelector("#videoCamera");
            if ("srcObject" in video) {
              video.srcObject = stream;
            } else {
              video.src =
                (window.URL && window.URL.createObjectURL(stream)) || stream;
            }
            video.play();
          })
          .catch(function (err) {
            console.log(err);
          });
      });
    },
    // 重拍
    resetCamera() {
      this.isShowCamera = true;
      this.blobFileCamera = "";
      this.openCamera();
    },
    // 关闭相机
    closeCamera() {
      this.mediaStreamCamera.getVideoTracks().forEach(function (track) {
        track.stop();
      });
      this.paisheModal = false;
    },
    // 点击拍摄
    setImage() {
      const that = this;
      that.isShowCamera = false;
      const video = document.querySelector("#videoCamera");
      const canvas = document.querySelector("#canvasCamera");
      canvas
        .getContext("2d")
        .drawImage(video, 0, 0, that.videoWidth, that.videoHeight);
      this.mediaStreamCamera.getVideoTracks().forEach(function (track) {
        track.stop();
      });
      const dataurl = canvas.toDataURL("image/jpg");
      // this.blobFileCamera = that.base64ToFile(dataurl, 'camera')
      this.blobFileCamera = dataurl;
    },
    // 确认拍摄
    enterCamera() {
      this.isShowCropper = true;
      this.paisheModal = false;
      this.isShowCamera = true;
      // return false
      // const myFile = this.blobFileCamera
      // const formData = new FormData()
      // formData.append('file', myFile)
      // formData.append('folder', 'MEMBER_IMG')
      // // 文件对象
      // // 获取卡类型列表
      // // return;
      // this.cameraLoading = true
      // uploadFiles(formData)
      //   .then((res) => {
      //     this.cameraLoading = false
      //     this.$set(this.param, 'faceUrl', res.insertUrl)
      //     this.$set(this.param, 'showFaceUrl', res.showUrl)
      //     this.blobFileCamera = ''
      //     this.paisheModal = false
      //   })
      //   .catch((err) => {
      //     this.cameraLoading = false
      //     console.log('err', err)
      //   })
    },
    base64ToFile(base64, fileName) {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      const data = base64.split(",");
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      const type = data[0].match(/:(.*?);/)[1];
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      const suffix = type.split("/")[1];
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1]);
      // 获取解码结果字符串的长度
      let n = bstr.length;
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n);
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n);
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type,
      });
      // 将File文件对象返回给方法的调用者
      return file;
    },
    getCardNum() {
      collectCard({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          shopId: localStorage.getItem("shopId"),
        },
      }).then((res) => {
        if (res.errorCode === "000000") {
          this.$set(this.param, "entityNumber", res.record.card);
        }
      });
    },
    acquisitionFace() {
      this.caijiLoading = true;
      collectFace({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          shopId: localStorage.getItem("shopId"),
        },
      }).then(
        (res) => {
          this.caijiLoading = false;
          if (res.errorCode === "000000") {
            this.$set(this.param, "faceUrl", res.record.insertUrl);
            this.$set(this.param, "showFaceUrl", res.record.showUrl);
          }
        },
        () => {
          this.caijiLoading = false;
        }
      );
    },
    cropperCameraClose() {
      this.isShowCropper = false;
      this.blobFileCamera = "";
    },
    // cropperCameraSubmit(){
    // },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw);
        this.fileinfo = file.raw;
        this.dialogCropperVisible = true;
      });
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      this.isShowCropper = false;
      this.blobFileCamera = "";
      if (config.success) {
        this.$set(this.param, "faceUrl", config.insertUrl);
        this.$set(this.param, "showFaceUrl", config.showUrl);
        this.fileinfo = config;
        this.dialogCropperVisible = false;
      } else {
        this.$message.error(config.msg || this.$t("message.scsb"));
        this.dialogCropperVisible = false;
      }
    },
    // async addFileChange(file, fileList) {
    //   // 上传，拿到file文件
    //   this.files = file.raw
    //   this.$nextTick(() => {
    //     this.optionImg = URL.createObjectURL(file.raw)
    //     this.fileinfo = file.raw
    //     this.dialogCropperVisible = true
    //   })
    // },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false;
    },
    deleteDeviceConfigAddImage(file, fileList) {
      this.param.faceUrl = "";
      this.param.showFaceUrl = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.img_warp {
  display: flex;
  justify-items: center;
  align-items: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 20px;
  .delete {
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    align-items: center;
    justify-content: center;
    .icon {
      color: #fff;
    }
  }
  &:hover {
    .delete {
      display: flex;
    }
  }
}
.code-style {
  width: 70%;
}
.code-btn-style {
  margin-left: 20px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}

.card-style {
  display: inline-block;
  vertical-align: middle;
  width: 23%;
  height: 220px;
  margin-right: 10px;
  margin-bottom: 10px;
  img {
    width: 80%;
    height: 111px;
    margin-top: 20px;
    margin-left: 10%;
    vertical-align: bottom;
    padding: 0;
    border-radius: 4px;
  }
  .card-name {
    color: #222;
    font-size: 18px;
    font-weight: 500;
    margin-top: 15px;
    margin-left: 20px;
    padding: 0;
    line-height: 18px;
    // background-color: red;
  }
  .card-first-price {
    color: #dd0707;
    font-size: 20px;
    font-weight: 600;
    margin-top: 16px;
    margin-left: 20px;
  }
}
.select-style {
  border: solid 3px #1943a9;
}
.normal-style {
  border: solid 1px #d8d8d8;
}
.base-message-style {
  width: 50%;
  display: inline-block;
  .base-value-style {
    font-size: 13px;
  }
  .card-name-style {
    display: inline-block;
    border: 1px #999 solid;
    border-radius: 4px;
    background-color: #fff;
    font-size: 12px;
    padding-left: 5px;
    padding-right: 5px;
    height: 20px;
    line-height: 20px;
    margin-top: 10px;
    padding-bottom: -15px;
    text-align: center;
  }
}

.btns-style {
  // width: 80%;
  margin-left: 10%;
}
.money-value-style {
  color: #dd0707;
  font-weight: 500;
}

.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
</style>
